package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.criteria.Predicate;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.dao.service.BaseAppDAO;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.dao.SysUserDAO;
import com.ruoyi.system.dao.SysRoleUserDAO;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysRoleUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
	private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

	@Autowired
    private BaseAppDAO baseDAO;

	@Autowired
	private SysUserDAO userDAO;

	@Autowired
	private ISysRoleService sysRoleService;

	@Autowired
	private ISysPostService sysPostService;

	@Autowired
	private SysRoleUserDAO userRoleDAO;

	@Autowired
	private ISysConfigService configService;

	@Autowired
	protected Validator validator;

	/**
	 * 根据条件分页查询用户列表
	 * 
	 * @param user
	 *            用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	public List<SysUser> selectUserList(SysUser user) {

		return userDAO.findAll(getSpecification(user));
	}

	@Override
	public Page<SysUser> selectUserList(SysUser config, Pageable pageinfo) {
		return userDAO.findAll(getSpecification(config),pageinfo);
	}

	private Specification<SysUser> getSpecification(SysUser config){
		return (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicateList = new ArrayList<>();
			if (!StringUtils.isNull(config.getUserId())) {
				predicateList.add(criteriaBuilder.equal(root.get("userId"), config.getUserId()));
			}
			if (!StringUtils.isEmpty(config.getUserName())) {
				predicateList.add(criteriaBuilder.like(root.get("userName"), "%"+config.getUserName()+"%"));
			}
			if (!StringUtils.isNull(config.getStatus())) {
				predicateList.add(criteriaBuilder.equal(root.get("status"), config.getStatus()));
			}

			if (!StringUtils.isNull(config.getPhonenumber())) {
				predicateList.add(criteriaBuilder.equal(root.get("phonenumber"), config.getPhonenumber()));
			}

			if (!StringUtils.isNull(config.getParams().get("beginTime"))) {
				predicateList.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), (String)config.getParams().get("beginTime")));
			}

			if (!StringUtils.isNull(config.getParams().get("endTime"))) {
				predicateList.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), (String)config.getParams().get("endTime")));
			}

			Predicate[] p = new Predicate[predicateList.size()];
			return criteriaBuilder.and(predicateList.toArray(p));
		};

	}

	/**
	 * 根据条件分页查询已分配用户角色列表
	 *
	 * @param user
	 *            用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	// @DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> selectAllocatedList(SysUser user) {
		String querysql = " select distinct u.user_id, u.dept_id, u.user_name, u.nick_name, u.email, u.phonenumber, u.status, u.create_time ";
		querysql += " from sys_user u  left join sys_dept d on u.dept_id = d.dept_id ";
		querysql += " left join sys_role_user ur on u.user_id = ur.user_id ";
		querysql += " left join sys_role r on r.role_id = ur.role_id ";
		querysql += "  where u.del_flag = '0' ";
		if (StringUtils.isNotEmpty(user.getUserName())) {
			querysql += " AND u.user_name like concat('%', '"+user.getUserName()+"', '%') ";
		}

		if (StringUtils.isNotEmpty(user.getPhonenumber())) {
			querysql += " AND u.phonenumber like concat('%', '"+user.getPhonenumber()+"', '%') ";
		}

		List<SysUser> list = baseDAO.createNativeQuery(querysql,SysUser.class);

		return list;


	}

	/**
	 * 根据条件分页查询未分配用户角色列表
	 * 
	 * @param user
	 *            用户信息
	 * @return 用户信息集合信息
	 */
	@Override
	// @DataScope(deptAlias = "d", userAlias = "u")
	public List<SysUser> selectUnallocatedList(SysUser user) {
		String querysql = " select distinct u.user_id, u.dept_id, u.user_name, u.nick_name, u.email, u.phonenumber, u.status, u.create_time ";
		querysql += " from sys_user u  left join sys_dept d on u.dept_id = d.dept_id ";
		querysql += " left join sys_role_user ur on u.user_id = ur.user_id ";
		querysql += " left join sys_role r on r.role_id = ur.role_id ";
		querysql += "  where u.del_flag = '0' and ( r.role_id IS NULL )";
		querysql += " and u.user_id not in (select u.user_id from sys_user u inner join sys_role_user ur on u.user_id = ur.user_id ) ";
		
		if (StringUtils.isNotEmpty(user.getUserName())) {
			querysql += " AND u.user_name like concat('%', '"+user.getUserName()+"', '%') ";
		}

		if (StringUtils.isNotEmpty(user.getPhonenumber())) {
			querysql += " AND u.phonenumber like concat('%', '"+user.getPhonenumber()+"', '%') ";
		}
		
		List<SysUser> list = baseDAO.createNativeQuery(querysql,SysUser.class);
		
		return list;
	}

	/**
	 * 通过用户名查询用户
	 *
	 * @param userName 用户名
	 * @return 用户对象信息
	 */
	@Override
	public List<SysUser> selectUserByUserName(String userName) {
		return userDAO.findByUserName(userName);
	}

	/**
	 * 通过用户ID查询用户
	 * 
	 * @param userId
	 *            用户ID
	 * @return 用户对象信息
	 */
	@Transactional
	@Override
	public SysUser selectUserById(String userId) {
		//TODO 查询用户时的角色和岗位信息 数据需要重新组织
		SysUser user = userDAO.getById(userId);
		return user;
	}

	/**
	 * 查询用户所属角色组
	 * 
	 * @param userName
	 *            用户名
	 * @return 结果
	 */
	@Override
	public String selectUserRoleGroup(String userName) {
		List<SysRole> list = sysRoleService.selectRolesByUserName(userName);
		if (CollectionUtils.isEmpty(list)) {
			return StringUtils.EMPTY;
		}
		return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
	}

	/**
	 * 查询用户所属岗位组
	 * 
	 * @param userName
	 *            用户名
	 * @return 结果
	 */
	@Override
	public String selectUserPostGroup(String userName) {
		List<SysPost> list = sysPostService.selectPostsByUserName(userName);
		if (CollectionUtils.isEmpty(list)) {
			return StringUtils.EMPTY;
		}
		return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
	}

	/**
	 * 校验用户名称是否唯一
	 * 
	 * @param userName
	 *            用户名称
	 * @return 结果
	 */
	@Override
	public String checkUserNameUnique(String userName) {
		List<SysUser> user = userDAO.findByUserName(userName);
		if (user != null && user.size() > 0) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	/**
	 * 校验手机号码是否唯一
	 *
	 * @param user
	 *            用户信息
	 * @return
	 */
	@Override
	public String checkPhoneUnique(SysUser user) {
		String userId = StringUtils.isNull(user.getUserId()) ? "" : user.getUserId();
		SysUser info = userDAO.findByPhonenumber(user.getPhonenumber());
		if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId)) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	/**
	 * 校验email是否唯一
	 *
	 * @param user
	 *            用户信息
	 * @return
	 */
	@Override
	public String checkEmailUnique(SysUser user) {
		String userId = StringUtils.isNull(user.getUserId()) ? "" : user.getUserId();
		SysUser info = userDAO.findByEmail(user.getEmail());
		if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId)) {
			return UserConstants.NOT_UNIQUE;
		}
		return UserConstants.UNIQUE;
	}

	/**
	 * 校验用户是否允许操作
	 * 
	 * @param user
	 *            用户信息
	 */
	@Override
	public void checkUserAllowed(SysUser user) {
		if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
			throw new ServiceException("不允许操作超级管理员用户");
		}
	}

	/**
	 * 校验用户是否有数据权限
	 * 
	 * @param userId
	 *            用户id
	 */
	@Override
	public void checkUserDataScope(String userId) {
		if (!SysUser.isAdmin(SecurityUtils.getUsername())) {
			SysUser user = new SysUser();
			user.setUserId(userId);
			List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
			if (StringUtils.isEmpty(users)) {
				throw new ServiceException("没有权限访问用户数据！");
			}
		}
	}

	/**
	 * 新增保存用户信息
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	@Transactional
	public SysUser insertUser(SysUser user) {
		return userDAO.save(user);
	}

	/**
	 * 注册用户信息
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	public boolean registerUser(SysUser user) {
		userDAO.save(user);
		return true;
	}

	/**
	 * 修改保存用户信息
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	@Transactional
	public SysUser updateUser(SysUser user) {

		return userDAO.save(user);
	}

	/**
	 * 修改用户状态
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	public int updateUserStatus(SysUser user) {
		userDAO.save(user);
		return 1;
	}

	/**
	 * 修改用户基本信息
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Override
	public int updateUserProfile(SysUser user) {
		userDAO.save(user);
		return 1;
	}

	/**
	 * 修改用户头像
	 * 
	 * @param userName
	 *            用户名
	 * @param avatar
	 *            头像地址
	 * @return 结果
	 */
	@Transactional
	@Override
	public boolean updateUserAvatar(String userName, String avatar) {
		return userDAO.updateUserAvatar(userName, avatar) > 0;
	}

	/**
	 * 重置用户密码
	 * 
	 * @param user
	 *            用户信息
	 * @return 结果
	 */
	@Transactional
	@Override
	public int resetPwd(SysUser user) {
		userDAO.resetUserPwd(user.getUserId(),user.getPassword());
		return 1;
	}

	/**
	 * 重置用户密码
	 * 
	 * @param userId
	 *            用户名
	 * @param password
	 *            密码
	 * @return 结果
	 */
	@Transactional
	@Override
	public int resetUserPwd(String userId, String password) {
		return userDAO.resetUserPwd(userId, password);
	}


	/**
	 * 通过用户ID删除用户
	 * 
	 * @param userId
	 *            用户ID
	 * @return 结果
	 */
	@Override
	@Transactional
	public int deleteUserById(String userId) {
		//TODO 删除用户的同时应该删除分配的角色，或者校验有分配的角色不允许删除
		userDAO.deleteById(userId);
		return 1;
	}

	/**
	 * 批量删除用户信息
	 * 
	 * @param userIds
	 *            需要删除的用户ID
	 * @return 结果
	 */
	@Override
	@Transactional
	public int deleteUserByIds(String[] userIds) {
		for (String userId : userIds) {
			checkUserAllowed(new SysUser(userId));
			checkUserDataScope(userId);
		}
		userDAO.deleteAllByIdInBatch(Arrays.asList(userIds));
		return 1;
	}

	/**
	 * 导入用户数据
	 * 
	 * @param userList
	 *            用户数据列表
	 * @param isUpdateSupport
	 *            是否更新支持，如果已存在，则进行更新数据
	 * @param operName
	 *            操作用户
	 * @return 结果
	 */
	@Override
	public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
		if (StringUtils.isNull(userList) || userList.size() == 0) {
			throw new ServiceException("导入用户数据不能为空！");
		}
		int successNum = 0;
		int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		String password = configService.selectConfigByKey("sys.user.initPassword");
		for (SysUser user : userList) {
			try {
				// 验证是否存在这个用户
				List<SysUser> u = userDAO.findByUserName(user.getUserName());
				if (StringUtils.isNull(u)) {
					BeanValidators.validateWithException(validator, user);
					user.setPassword(SecurityUtils.encryptPassword(password));
					user.setCreateBy(operName);
					this.insertUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
				} else if (isUpdateSupport) {
					BeanValidators.validateWithException(validator, user);
					user.setUpdateBy(operName);
					this.updateUser(user);
					successNum++;
					successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
				} else {
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
				}
			} catch (Exception e) {
				failureNum++;
				String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
				failureMsg.append(msg + e.getMessage());
				log.error(msg, e);
			}
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		} else {
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

	/**
	 * 根据用户id查询密码
	 *
	 * @param userId
	 * @return
	 */
	@Override
	public String findPasswordByUserId(String userId) {
		return userDAO.findPasswordByUserId(userId);
	}

	@Transactional
	@Override
	public int updateUserLoginInfo(String userId, String loginIp, Date loginDate) {
		return userDAO.updateUserLoginInfo(userId, loginIp, loginDate);
	}
}
